#coding:utf-8

## html 解析

from HTMLParser  import HTMLParser

#用于首页的html解析处理 
class HomePageHTMLParser(HTMLParser):
    title = ""
    title_tag = 0
    menu_tag = 0
    def __init__(self , tag ):
        HTMLParser.__init__(self)
        self.links = []
        self.tag = tag
            
    def handle_starttag(self, tag, attrs):
        #print "Encountered the beginning of a %s tag" % tag
        if tag == "a":

            if len(attrs) == 0 : pass
            else:
                title = False 
                href = False
                for [att , val ] in attrs :
                    try:
                        if att == "title" and  len(val.split(self.tag)) >1 :
                            title = True
                    except ValueError as e:
                        title = False

                    if att == "href":
                        href = val

                if  title :
                    self.links.append( [href, ""] )
                    self.menu_tag= len(self.links)
        if tag == "title":
            self.title_tag = 1
                
    def handle_data(self, data):
        if self.title_tag ==1 :
            self.title = data 
            self.title_tag = 0

        if self.menu_tag > 0:
            self.links[self.menu_tag - 1 ][1] = data
            self.menu_tag = 0

import httplib2

def BuildHomePage(domain , url , tag , call):
    h2 = httplib2.Http('.cache')
    resp2,content2 = h2.request(url)
    hp  = HomePageHTMLParser(tag)
    hp.feed(content2)
    hp.close()
    #print(hp.links)
    Book = {}
    h2 = httplib2.Http('.cache')
    for Item  in hp.links:
        print ("%s:%s" %  (Item[0]  ,Item[1]) )
        if Item[0][0:7] == "http://":
            resp2,content2 = h2.request(Item[0])
        else:
            resp2,content2 = h2.request(domain + Item[0])

        info = GetCartoonInfo(content2)
        if Book.has_key("name") == False:
            Book["name"] = info["name"]
        if not Book.has_key("list"):
            Book["list"] = []
        Book["list"].append(info)

    call(Book) 

import re


import json

'''
var g_comic_name = "寄生兽";
var g_chapter_name = "完全版第1卷";
var g_comic_url = "jss/";
var g_chapter_url = "jss/16322.shtml";
var next_chapter_pages = '["y\/%E5%AE%87%E5%AE%99%E5%88%91%E8%AD%A6\/VOL02\/001.jpg","y\/%E5%AE%87%E5%AE%99%E5%88%91%E8%AD%A6\/VOL02\/002.jpg","y\/%E5%AE%87%E5%AE%99%E5%88%91%E8%AD%A6\/VOL02\/003.jpg"]';
var g_current_page = 1;
var g_max_pic_count = 139;
'''
#pv8 = PyV8.JSContext()
import os
def GetCartoonInfo(content2 ):
    allline = content2.split("\n")
    info = {
        "name":"",
        "title":"",
        "max_page":0,
        "all_page":None,
    }


    for line in allline:
        if info["name"] == "":
            data = re.findall("var g_comic_name = \"(.*)\";" , line)
            if len(data) > 0:
                info["name"] = str(data[0])
                continue
        if info["title"] == "":
            data = re.findall("var g_chapter_name = \"(.*)\";" , line)
            if len(data)>0:
                info["title"] = str(data[0])
                continue
        if info["max_page"] == 0:
            data = re.findall("var g_max_pic_count = (.*);" , line)
            if len(data)>0:
                info["max_page"] = int(data[0])
                continue
        if info["all_page"] == None:
            data = re.findall("(eval\(.*\)\))" , line)
            if len(data)>0:
                tmpjs = open("tmp.js" , "wb")
                tmpjs.write(data[0]+";print(pages);")
                tmpjs.close()
                out = os.popen("v8 tmp.js")
                info["all_page"] = json.loads(out.read())
                #try:
                #    #pv8.enter()
                #    #pv8.eval(data[0]+";")
                #    #info["all_page"] = pv8.eval(pv8.eval("pages"))
                #except PyV8.JSError as e:
                #    print("all_page js error!"  , str(data[0]))
        
    return info

